/**
 * Copyright (C), 2015-2018, XXX有限公司
 * FileName: SendSms
 * Author:   sjkyll
 * Date:     2018-07-31 12:05
 * Description:
 * <author>          <time>          <version>          <desc>
 * 作者姓名         修改时间           版本号            描述
 */
package com.cdqidi.smsservice.service;

import SoftFan.Client.tcp.sendPoolFactory;
import SoftFan.EAI.runtime.message.dataBoxMessage;
import SoftFan.workflow.protocol.EAI.eaiException;
import com.cdqidi.smsservice.dto.AjaxResult;
import com.cdqidi.smsservice.dto.CoreMessage;
import com.cdqidi.smsservice.dto.SmsMessage;
import com.cdqidi.smsservice.exception.ApiException;
import com.cdqidi.smsservice.util.ApiLoginUtil;
import com.cdqidi.smsservice.util.TextUnit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import sessionFilterClient.msg.MSG_SocketSender;
import sessionFilterClient.msg.Socket_Exception;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * 〈一句话功能简述〉<br>
 *
 * @author sjkyll
 * @create 2018-07-31 12:05
 * @since 1.0.0
 */
@Service
@Slf4j(topic="SysInfo")
public class SendSmsService {
//    private static final Logger logger = LoggerFactory.getLogger("SysInfo");
    private final TextUnit textUnit;

    @Value(value = "${cmpp.core_server_ip}")
    private String core_server_ip;
    @Value(value = "${cmpp.core_server_port}")
    private Integer core_server_port;

    @Autowired
    public SendSmsService(TextUnit textUnit) {
        this.textUnit = textUnit;
    }


    public Integer sendAp(SmsMessage msg) throws ApiException {
        List<String[]> list = new ArrayList<>();
        String[] mobiles = msg.getMobile().split(",");
        String s[];
        String[] __mobiles;
            for (String mobile : mobiles) {
                s = new String[2];
                if(mobile.indexOf("#")!=-1){
                    __mobiles = mobile.split("#");
                    if (__mobiles.length != 2) {
                        throw new ApiException(AjaxResult.filedError("mobile异常"));
                    }
                    s[0] = __mobiles[0];
                    if(null==msg.getSmid()||"".equals(msg.getSmid())){
                        s[1] = __mobiles[1];
                    }else{
                        s[1] = msg.getSmid();
                    }
                }else{
                    s[0] = mobile;
                    s[1] = msg.getSmid();
                }

                list.add(s);
        }

        int idx = 1;

        for (String[] _mobiles : list) {
            if (_mobiles[0].length() != 11) {
                throw new ApiException(AjaxResult.filedError("手机号码位数不正确"));
            }
            if (idx > 100) {
                throw new ApiException(AjaxResult.filedError("手机号码最多支持100个"));
            }
            idx++;
        }
        String srcID = "10657062290838";
        String other_type = "1";
        String postage_type = "00";
        String postage_code = "01";
        String Url_title = "pushTitle";
        String Url = "http://";
        Integer function_id = 10;
        String isWAP = "1";
        String exescheck_code = "1";
        sendPoolFactory.getInstance().startup();
        MSG_SocketSender cmd = new MSG_SocketSender(core_server_ip, core_server_port, 13001, "admin", "admin");
        // 选择通道
        switch (msg.getChannelid()) {
            // 省移动
            case 10:
                other_type = "1";
                break;
            case 11:
                // 全网移动手机
                srcID = "106571256164248";
                other_type = "2";
                break;
            case 12:
                // 全网（移动、电信、联通 壹通道）
                srcID = "10657061231";
                other_type = "3";
                break;
            case 13:
                srcID = "106571256164248";
                other_type = "4";
                break;
            case 14:
                //卓望移动
                srcID = "10657061231";
                other_type = "1101";
                break;
            case 15:
                //微网通联
                srcID = "10657061231";
                other_type = "1102";
                break;
            default:
                throw new ApiException(AjaxResult.filedError("channelid异常"));
        }
        int coreLevel = 0;
        // 如果学校签名为空，则签名为空字符串
        String _content = msg.getContent();
        CoreMessage coreMessage;

        for (String[] _mobiles : list) {
            coreMessage = new CoreMessage();
            // 将参数压入到CoreMessage中。
            coreMessage.setAuto_id(UUID.randomUUID().toString());
            coreMessage.setSm_id(_mobiles[1]);
            // 信息类型，及时短信、定时短信、wap推送
            coreMessage.setMsgtype("1");
            coreMessage.setSrc_sum(srcID);
            coreMessage.setBody(_content);
            coreMessage.setDest_sum(_mobiles[0]);
            coreMessage.setFeetype(postage_code);
            coreMessage.setFeecode(postage_type);
            coreMessage.setPush_title(Url_title);
            coreMessage.setPush_url(Url);
            coreMessage.setSchoolid(msg.getSchoolid());
            coreMessage.setExescheck_code(exescheck_code);
            //网关发送优先级
            coreMessage.setLevel(coreLevel);
            coreMessage.setUid(msg.getUserid());
            coreMessage.setIs_push(isWAP);
            coreMessage.setFunction_id(function_id);
            coreMessage.setOther_type(other_type);
            coreMessage.setSign(msg.getSign());
            coreMessage.setUsertype("1");
            if (null != msg.getUserType() && !msg.getUserType().equals("")) {
                coreMessage.setUsertype(msg.getUserType());
            }
            if (msg.getSmlevel() == null) {
                coreMessage.setExtCode("01");
            } else {
                coreMessage.setExtCode(msg.getSmlevel() + "");
            }
            try {
                if (null == msg.getIsLong() || msg.getIsLong() == 0) {
                    send(cmd, coreMessage);
                } else {
                    sendLong(cmd, coreMessage);
                }
            } finally {
                coreMessage.freeData();
            }
        }
        msg.freeData();
        return list.size();
    }

    private void send(MSG_SocketSender cmd, CoreMessage message) throws ApiException {
        try {
            String content = message.getBody();
            String sign = message.getSign();
            int signLen = 0;
            if (null != sign && !"".equals(sign)) {
                //签名不为空
                signLen = sign.length();
                content = content + sign;
            }
            String[] shortMessageSplit = textUnit.shortMessageSplit(content, signLen);
            String body;
            for (int i = 0; i < shortMessageSplit.length; i++) {
                body = shortMessageSplit[i];
                body = textUnit.crateSign(body, message.getSign());
                dataBoxMessage sender = new dataBoxMessage();
                sender.setSendMode("SOCKET");
                sender.setProperty("Command", "SmkernelPlug");
                sender.setProperty("EXECLEVEL", "1");
                HashMap<String, Object> data = new HashMap<>();
                data.put("auto_sn", message.getAuto_id().concat("x" + String.valueOf(i + 1)));
                data.put("msgtype", message.getMsgtype());
                data.put("src_num", getSrcNum(message.getSrc_sum()));
                data.put("function_id", message.getFunction_id());
                data.put("body", new String(body.getBytes("UnicodeBigUnmarked"), StandardCharsets.UTF_16));
                data.put("dest_num", message.getDest_sum());
                data.put("service_id", getServiceId(message.getSrc_sum()));
                data.put("feetype", message.getFeetype());
                data.put("feecode", message.getFeecode());
                data.put("at_time", "");
                data.put("push_title", message.getPush_title());
                data.put("push_url", message.getPush_url());
                data.put("level", message.getLevel());
                data.put("sp_id", message.getSpcode());
                data.put("check_code", message.getExescheck_code());
                data.put("school_id", message.getSchoolid());
                data.put("uid", message.getUid());
                data.put("is_push", "0");
                data.put("sm_sum", shortMessageSplit.length);
                data.put("sm_sort", i + 1);
                data.put("usertype", message.getUsertype());
                data.put("other_type", message.getOther_type());
                data.put("extCode", message.getExtCode());
                data.put("sm_id", message.getSm_id());
                sender.setBody(data);
                cmd.send(dataBoxMessage.BINARYMSG, sender.writeByteMsg());
                log.info("短信发送,appId: "+ ApiLoginUtil.getApiLogin().getAppId()+",ip: "+ApiLoginUtil.getApiLogin().getIp()+",手机号: "+message.getDest_sum());
            }
        } catch (IOException | eaiException | Socket_Exception e) {
            throw new ApiException(AjaxResult.smsSendError(e.getMessage()));
        }
    }

    private void sendLong(MSG_SocketSender cmd, CoreMessage message) throws ApiException {
        try {
            String body = textUnit.crateSign(message.getBody(), message.getSign());
            dataBoxMessage sender = new dataBoxMessage();
            sender.setSendMode("SOCKET");
            sender.setProperty("Command", "SmkernelPlug");
            sender.setProperty("EXECLEVEL", "1");
            HashMap<String, Object> data = new HashMap<>();
            data.put("auto_sn", message.getAuto_id());
            data.put("msgtype", "5");
            data.put("src_num", getSrcNum(message.getSrc_sum()));
            data.put("function_id", message.getFunction_id());
            data.put("body", body);
            data.put("dest_num", message.getDest_sum());
            data.put("service_id", getServiceId(message.getSrc_sum()));
            data.put("feetype", message.getFeetype());
            data.put("feecode", message.getFeecode());
            data.put("at_time", "");
            data.put("push_title", message.getPush_title());
            data.put("push_url", message.getPush_url());
            data.put("level", message.getLevel());
            data.put("sp_id", message.getSpcode());
            data.put("check_code", message.getExescheck_code());
            data.put("school_id", message.getSchoolid());
            data.put("uid", message.getUid());
            data.put("is_push", "0");
            data.put("sm_sum", 0);
            data.put("sm_sort", 0);
            data.put("usertype", message.getUsertype());
            data.put("other_type", message.getOther_type());
            data.put("extCode", message.getExtCode());
            data.put("sm_id", message.getSm_id());
            sender.setBody(data);
            cmd.send(dataBoxMessage.BINARYMSG, sender.writeByteMsg());
            log.info("长短信发送,appId: "+ ApiLoginUtil.getApiLogin().getAppId()+",ip: "+ApiLoginUtil.getApiLogin().getIp()+",手机号: "+message.getDest_sum());
        } catch (IOException | eaiException | Socket_Exception e) {
            throw new ApiException(AjaxResult.smsSendError(e.getMessage()));
        }
    }

    private String getSrcNum(String srcNum) {
        if (srcNum.equals("106570600000")) {
            return "106570603100062";
        }
        if (srcNum.length() > 21) {
            return srcNum.substring(0, 20);
        }
        return srcNum;
    }

    private String getServiceId(String srcId) {
        String msg = "ASC3911603";
        try {
            if (!"".equals(srcId) && null != srcId && srcId.length() > 9) {
                String string = srcId.substring(0, 10);
                if (string.equals("1065712561")) {
                    msg = "ASC3911604";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return msg;
    }
}